import axios from 'axios';
import MobileGameView from '../components/MobileGameView.vue';
import MobileHistoryView from '../components/MobileHistoryView.vue';
import CardAnimation from '../components/CardAnimation.vue';
import * as GameUtils from './GameUtils';
import { api } from './api'; // 导入统一的API接口

export default {
  name: 'App',
  components: {
    MobileGameView,
    MobileHistoryView,
    CardAnimation
  },
  data() {
    return {
      playerHand: [],
      bankerHand: [],
      playerPoints: 0,
      bankerPoints: 0,
      betChoice: '',
      betAmount: 1000,
      // 添加更多注码选项，分为3组
      betAmountOptions: [
        [0, 1000, 1100, 1300, 1700], // 第一组
        [2000, 2200, 2600, 3400],    // 第二组
        [3000, 3300, 3900, 5100]     // 第三组
      ],
      // 当前选择的组索引和金额
      selectedBetGroup: 0,   // 默认选择第一组
      history: [],
      resultsHistory: [],
      result: '',
      win: false,
      payout: 0,
      totalWinLoss: 0,
      cardsDealtCount: 0,   // 添加已发牌的数量
      maxCardsLimit: 400,   // 最大发牌数量
      remainingDeals: 0,    // 剩余可发牌次数
      gameEnded: false,     // 游戏是否结束
      betOptions: [
        { label: '闲', value: 'player', baseClass: 'bg-blue-200 text-blue-700 hover:bg-blue-300', activeClass: 'bg-blue-500 text-white scale-105' },
        { label: '庄', value: 'banker', baseClass: 'bg-pink-200 text-pink-700 hover:bg-pink-300', activeClass: 'bg-pink-500 text-white scale-105' },
        { label: '和', value: 'tie', baseClass: 'bg-green-200 text-green-700 hover:bg-green-300', activeClass: 'bg-green-500 text-white scale-105' },
      ],
      isMobile: false,
      isScreenSmall: false,
      showMobileHistory: false,
      showDealAnimation: false
    }
  },
  computed: {
    formattedRoadmap() {
      return GameUtils.formatRoadmap(this.resultsHistory);
    }
  },
  methods: {
    checkDevice() {
      // 检测是否是移动设备
      this.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
      // 检测屏幕尺寸
      this.isScreenSmall = window.innerWidth < 1024;
    },
    toggleMobileHistory() {
      this.showMobileHistory = !this.showMobileHistory;
    },
    updateBetAmount(amount) {
      this.betAmount = amount;
    },
    closeDealAnimation() {
      this.showDealAnimation = false;
    },
    async startGame() {
      try {
        console.log('点击了开始新游戏按钮...');
        // 添加UI反馈
        alert('正在开始新游戏...');
        
        const response = await api.game.resetGame();
        console.log('游戏开始成功, 响应:', response);
        alert('游戏开始成功!');
        
        // 重置游戏状态
        this.playerHand = [];
        this.bankerHand = [];
        this.playerPoints = 0;
        this.bankerPoints = 0;
        this.result = '';
        this.win = false;
        this.payout = 0;
        this.betChoice = '';
        this.gameEnded = false; // 重置游戏结束状态
        
        // 获取卡牌状态
        this.getCardsStatus();
      } catch (error) {
        console.error('开始游戏失败:', error);
        alert('开始游戏失败：' + (error.message || '无法连接到服务器'));
      }
    },
    async placeBet(choice) {
      this.betChoice = choice;
      console.log('设置下注选择为:', choice);
      try {
        console.log('Placing bet:', { choice, amount: this.betAmount });
        const response = await api.game.placeBet({
          bet_choice: choice,
          bet_amount: this.betAmount
        });
        console.log('Bet placed:', response);
      } catch (error) {
        console.error('Error placing bet:', error);
        alert('下注失败：' + (error.message || '未知错误'));
      }
    },
    async dealCards() {
      try {
        // 如果游戏已结束，提示用户并返回
        if (this.gameEnded) {
          alert('游戏已结束！已达到最大发牌数量400张，请开始新游戏。');
          return;
        }

        console.log('Dealing cards...');
        // 清空当前牌面显示
        this.playerHand = [];
        this.bankerHand = [];
        this.playerPoints = 0;
        this.bankerPoints = 0;
        
        console.log('当前下注选择:', this.betChoice, '金额:', this.betAmount);
        
        // 如果之前没有设置下注选择，确保先设置
        if (this.betAmount > 0 && !this.betChoice) {
          console.warn('警告：有下注金额但未选择下注项，将默认设置为"闲"');
          this.betChoice = 'player'; // 默认设置为闲
          
          // 同步到后端
          await this.placeBet(this.betChoice);
        }
        
        const response = await api.game.dealOnly();
        console.log('Cards dealt:', response);
        const data = response;

        // 检查是否已达到卡牌上限
        if (data.game_ended) {
          this.gameEnded = true;
          alert(`游戏结束！已达到最大发牌数量${data.max_cards_limit}张。`);
          return;
        }
        
        // 显示发牌动画
        this.showDealAnimation = true;
        
        // 设置结果数据，确保最多只有3张牌
        this.playerHand = data.player_hand.slice(0, 3);
        this.bankerHand = data.banker_hand.slice(0, 3);
        this.playerPoints = data.player_points;
        this.bankerPoints = data.banker_points;
        this.result = data.result;
        this.win = data.win;
        this.payout = data.payout;
        
        // 更新卡牌计数信息
        if (data.cards_dealt_count !== undefined) {
          this.cardsDealtCount = data.cards_dealt_count;
          this.maxCardsLimit = data.max_cards_limit;
          this.remainingDeals = data.remaining_deals;
          
          // 如果接近限制，显示警告
          if (data.remaining_deals <= 10 && data.remaining_deals > 0) {
            alert(`警告：剩余发牌次数仅剩${data.remaining_deals}次！`);
          }
        }
        
        console.log('游戏结果:', this.result);
        console.log('是否赢:', this.win);
        console.log('赔付:', this.payout);
        console.log('已发牌数量:', this.cardsDealtCount, '/', this.maxCardsLimit);
        
        // 始终更新路单，无论是否是观战模式
        this.resultsHistory.unshift(this.result);
        if (this.resultsHistory.length > 50) {
          this.resultsHistory = this.resultsHistory.slice(0, 50);
        }
        
        // 确保路单滚动到最新的列
        this.$nextTick(() => {
          this.scrollRoadmapToEnd();
        });
        
        // ================ 输赢计算逻辑开始 ================
        // 只有在有实际下注时才计算输赢
        if (this.betAmount > 0) {
          // 1. 首先确定真正的胜负结果：只有下注选择与结果相同才是赢
          const isWin = this.betChoice === this.result;
          console.log(`[输赢判定] 下注:${this.betChoice}, 结果:${this.result}, 是否获胜:${isWin}`);
          
          // 2. 重新计算赔付金额，确保正确
          let finalPayout = 0;
          if (isWin) {
            // 2.1 如果获胜，根据不同赔率计算
            if (this.betChoice === 'banker') {
              if (this.bankerPoints === 6) {
                // 庄6点赢，赔率为1:0.5
                finalPayout = this.betAmount * 0.5 + this.betAmount;
                console.log(`[赔付计算] 庄6点赢，赔率1:0.5，赔付:${finalPayout}`);
              } else {
                // 庄其他点数赔率为1:1
                finalPayout = this.betAmount * 2;
                console.log(`[赔付计算] 庄其他点赢，赔率1:1，赔付:${finalPayout}`);
              }
            } else if (this.betChoice === 'player') {
              // 闲赔率为1:1
              finalPayout = this.betAmount * 2;
              console.log(`[赔付计算] 闲赢，赔率1:1，赔付:${finalPayout}`);
            } else if (this.betChoice === 'tie') {
              // 和赔率为1:8
              finalPayout = this.betAmount * 9;
              console.log(`[赔付计算] 和赢，赔率1:8，赔付:${finalPayout}`);
            }
          } else {
            // 2.2 如果不是和局且输了，赔付为0；如果是和局，赔付为下注金额（返还本金）
            if (this.result === 'tie' && this.betChoice !== 'tie') {
              // 和局情况下，闲庄的下注返还本金
              finalPayout = this.betAmount;
              console.log(`[赔付计算] 和局，闲庄下注返还本金:${finalPayout}`);
            } else {
              // 真正输了
              finalPayout = 0;
              console.log(`[赔付计算] 您输了，赔付:${finalPayout}`);
            }
          }
          
          // 3. 计算净收益：
          // - 赢了是(赔付金额-下注金额)
          // - 输了是(-下注金额)
          // - 和局时闲庄下注返还本金，净收益为0
          let netProfit = 0;
          if (isWin) {
            // 赢了
            netProfit = finalPayout - this.betAmount;
          } else if (this.result === 'tie' && this.betChoice !== 'tie') {
            // 和局，闲庄下注返还本金，净收益为0
            netProfit = 0;
          } else {
            // 输了
            netProfit = -this.betAmount;
          }
          
          console.log(`[净收益计算] 下注金额:${this.betAmount}, 赔付:${finalPayout}, 净收益:${netProfit}`);
          
          // 4. 更新总输赢
          this.totalWinLoss += netProfit;
          console.log(`[总输赢更新] 更新后总输赢:${this.totalWinLoss}`);
          
          // 5. 创建历史记录条目
          const currentTime = new Date().toLocaleString();
          // win_or_lose: 1为赢，0为输，2为和局情况下的闲庄下注（不输不赢）
          const winLoseStatus = isWin ? 1 : (this.result === 'tie' && this.betChoice !== 'tie' ? 2 : 0);
          
          const historyRecord = {
            timestamp: currentTime,
            bet_choice: this.betChoice,
            bet_amount: this.betAmount,
            result: this.result,
            win_or_lose: winLoseStatus,
            payout: finalPayout,
            player_hand: this.playerHand,
            banker_hand: this.bankerHand,
            player_points: this.playerPoints,
            banker_points: this.bankerPoints
          };
          
          // 6. 将当前结果添加到历史记录的开头
          this.history.unshift(historyRecord);
          console.log('[历史记录] 已添加当前游戏记录');
        } else {
          // 观战模式：创建一个临时的历史记录对象，但不计入总输赢
          const currentTime = new Date().toLocaleString();
          const observeRecord = {
            timestamp: currentTime,
            bet_choice: this.betChoice || '观战',
            bet_amount: 0,
            result: this.result,
            win_or_lose: 0,
            payout: 0,
            player_hand: this.playerHand,
            banker_hand: this.bankerHand,
            player_points: this.playerPoints,
            banker_points: this.bankerPoints
          };
          
          // 将观战结果添加到历史记录的开头
          this.history.unshift(observeRecord);
        }
        
        // 由于我们已经手动更新了历史记录，所以不需要再从后端加载
        // await this.loadHistory();
      } catch (error) {
        console.error('Error dealing cards:', error);
        alert('发牌失败：' + (error.message || '未知错误'));
      }
    },
    async loadHistory() {
      try {
        console.log('Loading history...');
        const response = await api.game.getHistory();
        console.log('History loaded:', response);
        this.history = response;
        
        this.resultsHistory = this.history.map(item => item.result).reverse();
        this.calculateTotalWinLoss();
      } catch (error) {
        console.error('Error loading history:', error);
        alert('加载历史记录失败：' + (error.message || '未知错误'));
      }
    },
    async clearAllHistory() {
      try {
        if (!confirm('确定要清空所有历史数据吗？此操作不可恢复。')) {
          return;
        }
        
        console.log('Clearing all history...');
        const response = await api.game.clearHistory();
        console.log('History cleared:', response);
        
        // 重置所有状态
        this.playerHand = [];
        this.bankerHand = [];
        this.playerPoints = 0;
        this.bankerPoints = 0;
        this.result = '';
        this.win = false;
        this.payout = 0;
        this.history = [];
        this.resultsHistory = [];
        this.totalWinLoss = 0;
        
        alert('所有历史数据已清空');
      } catch (error) {
        console.error('Error clearing history:', error);
        alert('清空历史数据失败：' + (error.message || '未知错误'));
      }
    },
    calculateTotalWinLoss() {
      this.totalWinLoss = GameUtils.calculateTotalWinLoss(this.history);
    },
    translateResult(result) {
      return GameUtils.translateResult(result);
    },
    scrollRoadmapToEnd() {
      // 找到路单容器并滚动到最右侧
      const roadmapContainers = document.querySelectorAll('.overflow-x-auto');
      roadmapContainers.forEach(container => {
        if (container) {
          container.scrollLeft = container.scrollWidth;
        }
      });
    },
    async getCardsStatus() {
      try {
        const response = await api.game.getCardsStatus();
        console.log('Cards status:', response);
        const data = response;
        
        this.cardsDealtCount = data.cards_dealt_count;
        this.maxCardsLimit = data.max_cards_limit;
        this.remainingDeals = data.remaining_deals;
        
        // 检查是否已达到卡牌上限
        if (data.cards_dealt_count >= data.max_cards_limit) {
          this.gameEnded = true;
        }
      } catch (error) {
        console.error('Error getting cards status:', error);
      }
    }
  },
  mounted() {
    this.playerHand = [];
    this.bankerHand = [];
    this.playerPoints = 0;
    this.bankerPoints = 0;
    
    this.loadHistory();
    this.checkDevice();
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.checkDevice);
    
    // 获取卡牌状态
    this.getCardsStatus();
  },
  beforeUnmount() {
    // 移除事件监听器
    window.removeEventListener('resize', this.checkDevice);
  }
}; 